package com.smile.stream.group;

import com.smile.stream.pojo.Transaction;

import javax.jws.Oneway;
import java.util.ArrayList;
import java.util.Currency;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author LiYuhang
 * @version 0.1
 * @application
 * @Date 2021/10/7 20:28
 */
public class GroupDemo {
    /**
     * 把列表中的交易按货币分组
     * @param args
     */
    public static void main(String[] args) {
        groupInJava7();
        groupInJava8();

    }

    private static void groupInJava8() {
        List<Transaction> transactions=getListByCOndition();
        Map<Integer, List<Transaction>> collect = transactions.stream().collect(Collectors.groupingBy(Transaction::getLevel));
        collect.entrySet().forEach(System.out::println);
    }

    private static void groupInJava7() {
        List<Transaction> transactions=getListByCOndition();
        Map<Integer, List<Transaction>> transactionsByCurrencies = new HashMap<>();
        for (Transaction transaction : transactions) {
            Integer level = transaction.getLevel();
            List<Transaction> transactionList = transactionsByCurrencies.getOrDefault(level,new ArrayList<>());
            transactionList.add(transaction);
            transactionsByCurrencies.putIfAbsent(level,transactionList);
        }
        transactionsByCurrencies.entrySet().forEach(System.out::println);
    }

    private static List<Transaction> getListByCOndition() {
        ArrayList<Transaction> transactions = new ArrayList<>();
        transactions.add(new Transaction(1,"test1"));
        transactions.add(new Transaction(1,"test1"));
        transactions.add(new Transaction(1,"test1"));
        transactions.add(new Transaction(3,"test3"));
        transactions.add(new Transaction(2,"test2"));
        transactions.add(new Transaction(2,"test2"));
        return transactions;
    }
}
